package com.coollang.smartbra.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.coollang.smartbra.R;
import com.coollang.smartbra.activity.LoginActivity;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.interfaces.TextChangeListener;
import com.coollang.smartbra.presenter.ChangePassFragmentPresenter;
import com.coollang.smartbra.utils.StringUtils;
import com.coollang.smartbra.utils.ToastUtils;
import com.coollang.smartbra.utils.UIUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 忘记密码页面
 */

public class ChangePassFragment extends LoginBaseFragment implements View.OnClickListener {
    private static final String TAG = "ChangePassFragment";
    @BindView(R.id.rv_change)
    TextView mTvChange;
    private View view;
    private Context mContext;
    @BindView(R.id.et_phone_change)
    EditText etPhoneChange;
    @BindView(R.id.et_pass_change)
    EditText etPassChange;
    @BindView(R.id.et_code_change)
    EditText etCodeChange;
    @BindView(R.id.iv_clear_phone_change)
    ImageView ivClearPhone;
    @BindView(R.id.iv_see_pass_change)
    ImageView ivSeePass;
    @BindView(R.id.get_code)
    TextView tvGetCode;

    private ChangePassFragmentPresenter mFragmentPresenter1;
    private String mPhone;
    private String mPassword;
    private String mCode;

    @Override
    protected View inflateView(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.item_change_pass, null, false);
        return view;
    }

    @Override
    protected void initView(View view) {
        ButterKnife.bind(this, view);
        mContext = this.getActivity();
        initListener();
    }

    /**
     * 注册监听
     */
    private void initListener() {
        UIUtils.setLengthFilter(etPhoneChange, 11);
        UIUtils.setLengthFilter(etCodeChange, 4);
        UIUtils.setLengthFilter(etPassChange, 20);
        ivClearPhone.setOnClickListener(this);
        ivSeePass.setOnClickListener(this);
        tvGetCode.setOnClickListener(this);
        mTvChange.setOnClickListener(this);

        // 对手机号输入框做监听
        listenerPhoneEdit();

        // 对手机密码输入框做监听
        listenerPassWEdit();
    }

    private void listenerPhoneEdit() {
        etPhoneChange.addTextChangedListener(new TextChangeListener() {
            @Override
            public void onTextChange(String str) {
                if (str.length() == 0) {
                    ivClearPhone.setVisibility(View.GONE);
                } else {
                    ivClearPhone.setVisibility(View.VISIBLE);
                }

                if (str.length() == 1) {
                    int anInt = Integer.parseInt(str.subSequence(0, 1).toString());
                    if (anInt != 1) {
                        etPhoneChange.setText("");
                    }
                }
            }
        });
    }

    private void listenerPassWEdit() {
        etPassChange.addTextChangedListener(new TextChangeListener() {
            @Override
            public void onTextChange(String str) {
                if (str.length() == 0) {
                    ivSeePass.setVisibility(View.GONE);
                } else {
                    ivSeePass.setVisibility(View.VISIBLE);
                }

                if (str.contains(" ")) {
                    str = str.trim();
                    etPassChange.setText(str.trim());
                    etPassChange.setSelection(str.length());
                }
            }
        });
    }

    @Override
    protected void initData() {
        mFragmentPresenter1 = new ChangePassFragmentPresenter(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        tvGetCode.setClickable(true);
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_clear_phone_change:
                etPhoneChange.setText("");
                ivClearPhone.setVisibility(View.GONE);
                break;

            case R.id.iv_see_pass_change:
                UIUtils.seePassword(etPassChange, ivSeePass);
                break;
            case R.id.get_code:
                if (MyApplication.getApplication().hasNet()) {
                    tvGetCode.setClickable(false);
                    getCode();
                }
                break;

            case R.id.rv_change:
                if (MyApplication.getApplication().hasNet()) {
                    doChange();
                }
                break;
        }
    }

    /**
     * 获取短信验证码
     */
    private void getCode() {//判断手机号码是否符合格式、是否注册
        String phone = etPhoneChange.getText().toString();
        if (phone.length() == 0) {
            tvGetCode.setClickable(true);
            ToastUtils.showToast(UIUtils.getString(R.string.phone_null));
        } else if (!StringUtils.matchPhone(phone)) {
            //号码格式校验
            tvGetCode.setClickable(true);
            ToastUtils.showToast(UIUtils.getString(R.string.error_phone));
        } else {

            // 进行网络请求,判断是否注册
            setTime();
            mFragmentPresenter1.checkUserIsRegister(phone);
        }
    }

    /**
     * 修改密码
     */
    private void doChange() {
        mPhone = etPhoneChange.getText().toString();
        mPassword = etPassChange.getText().toString();
        mCode = etCodeChange.getText().toString();

        if (checkChangPassOK()) {
            // 网络请求
            mFragmentPresenter1.setChangePassInfo(mPhone, mPassword, mCode);
        }
    }

    // 验证是否可以更改密码
    private boolean checkChangPassOK() {
        boolean isCheckOk = true;

        if (TextUtils.isEmpty(mPhone)) {
            ToastUtils.showToast(UIUtils.getString(R.string.phone_null));
            isCheckOk = false;
        } else if (!StringUtils.matchPhone(mPhone)) {
            ToastUtils.showToast(UIUtils.getString(R.string.phone_wrong_match));
            isCheckOk = false;
        } else if (TextUtils.isEmpty(mCode)) {
            ToastUtils.showToast(UIUtils.getString(R.string.code_null));
            isCheckOk = false;
        } else if (mCode.length() < 4) {
            ToastUtils.showToast(UIUtils.getString(R.string.code_short));
            isCheckOk = false;
        } else if (TextUtils.isEmpty(mPassword)) {
            ToastUtils.showToast(UIUtils.getString(R.string.pass_null));
            isCheckOk = false;
        } else if (mPassword.length() < 6) {
            ToastUtils.showToast(UIUtils.getString(R.string.pass_short));
            isCheckOk = false;
        }

        return isCheckOk;
    }

    private Handler mHandler = new Handler();

    private int time = 60;

    private void setTime() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (time < 0) {
                    time = 60;
                    tvGetCode.setClickable(true);
                    tvGetCode.setText(R.string.get_code);
                } else {
                    String str = mContext.getResources().getString(R.string.get_code_again);
                    tvGetCode.setText(str + "(" + time + ")");
                    // setTime();
                    time--;

                    mHandler.postDelayed(this, 1000);
                }
            }
        });
    }


    public void changePassSucceed() {
        ToastUtils.showToast("修改成功");

        // 切换到注册页面,同时将手机号码也切换过去
        LoginActivity activity = (LoginActivity) mContext;
        activity.goToLoginView();
        // 向注册页面传递手机号码
        activity.getBaseFragment().setLoginrPhone(etPhoneChange.getText().toString());
    }

    public void userIsRegister() {
        time = -1;
        tvGetCode.setClickable(true);
    }

    private void showIsLoginDialog() {
        AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.setMessage("该手机号未注册");
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "去注册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 切换到注册页面,同时将手机号码也切换过去
                LoginActivity activity = (LoginActivity) mContext;
                activity.goToRegistView();
                // 向注册页面传递手机号码
                activity.getBaseFragment().setRegisterPhone(etPhoneChange.getText().toString());
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        Button posiviveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        posiviveButton.setTextColor(Color.parseColor("#F79444"));
        Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        negativeButton.setTextColor(Color.parseColor("#000000"));
    }

    // ==========================================
    public void onIsRegister(int data) {
        if (data == 1) {
            // 已经注册,可以发送验证码
            mFragmentPresenter1.sendSMSCode(etPhoneChange.getText().toString().trim());
        } else {
            // 没有注册,停止计时
            userIsRegister();
            showIsLoginDialog();
        }
    }
}
